<template>
  <div class="find">
    <div class="search">
      <span class="arrow-left" @click="goBack">‹</span>
      <van-search
          v-model="searchValue"
          placeholder="请输入商品名称"
          @search="onSearch"
      />
    </div>
    <div class="discover-container">
      <div class="sidebar">
        <van-cell-group>
          <van-cell
              v-for="category in categories"
              :key="category.name"
              :title="category.name"
              :class="{ active: activeCategory === categories.indexOf(category) }"
              @click="activeCategory = categories.indexOf(category)"
          />
        </van-cell-group>
      </div>
      <div class="content">
        <div v-if="categories[activeCategory]" v-for="item in categories[activeCategory].items" :key="item.title">
          <h3>{{ item.title }}</h3>
          <div
              v-for="product in item.products"
              :key="product.name"
              :id="product.name"
              :class="{ highlight: highlightedProduct === product.name }"
          >
            <!-- 传递店铺索引和商品信息 -->
            <ProductList :products="[product]" :storeIndex="item.storeIndex"/>
          </div>
        </div>
      </div>
    </div>
    <TabBar/>
    <!-- 使用弹窗组件 -->
    <Modal
        v-model:show="showModal"
        title="未找到商品"
        message="您搜索的商品不存在，请重新输入。"
        @close="showModal = false"
    />
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import axios from 'axios';
import ProductList from '@/components/ProductList.vue';
import TabBar from "@/components/TabBar.vue";
import Modal from '@/components/Modal.vue';
import {useRouter} from "vue-router";

const searchValue = ref('');
const activeCategory = ref(0);
const highlightedProduct = ref('');
const showModal = ref(false);
const router = useRouter();
const goBack = () => {
  router.push({name: 'home'});
}
const categories = ref([]);

onMounted(async () => {
  try {
    const response = await axios.get('http://127.0.0.1:8000/app/stores/');
    console.log('API Response:', response.data);
    categories.value = formatCategories(response.data);
    console.log(categories.value);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
});

function formatCategories(data) {
  const categoriesMap = new Map();

  data.forEach(store => {
    store.products.forEach(product => {
      if (!categoriesMap.has(store.type)) {
        categoriesMap.set(store.type, {
          name: store.type,
          items: []
        });
      }
      const category = categoriesMap.get(store.type);
      category.items.push({
        title: store.name,
        storeIndex: store.id,
        products: [
          {
            name: product.name,
            image: product.img,
            details: product.details,
          }
        ]
      });
    });
  });

  return Array.from(categoriesMap.values());
}

const onSearch = async (value) => {
  let found = false;
  highlightedProduct.value = '';

  if (value) {
    try {
      const response = await axios.get(`http://127.0.0.1:8000/app/search/`, {
        params: {query: value}
      });
      console.log('Search API Response:', response.data);
      const searchResults = response.data;
      if (searchResults.length > 0) {
        categories.value = formatCategoriesForSearch(searchResults);
        found = true;
      } else {
        showModal.value = true; // 显示弹窗
      }
    } catch (error) {
      console.error('Error searching products:', error);
      showModal.value = true; // 显示弹窗
    }
  } else {
    try {
      const response = await axios.get('http://127.0.0.1:8000/menu/api/stores/');
      console.log('API Response:', response.data);
      categories.value = formatCategories(response.data);
      console.log(categories.value);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  }
};

function formatCategoriesForSearch(data) {
  const categoriesMap = new Map();

  data.forEach(item => {
    const storeType = item.store_type; // 使用店铺分类作为键
    if (!categoriesMap.has(storeType)) {
      categoriesMap.set(storeType, {
        name: storeType, // 分类名称使用店铺分类
        items: []
      });
    }
    const category = categoriesMap.get(storeType);
    category.items.push({
      title: item.store_name, // 使用店铺名称作为标题
      storeIndex: 0, // 这里假设店铺索引为0，因为搜索结果不区分店铺
      products: [
        {
          name: item.name,
          image: item.img,
          details: item.details,
        }
      ]
    });
  });

  return Array.from(categoriesMap.values());
}
</script>


<style scoped>
.find {
  padding-bottom: 100px;
}

.search {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.arrow-left {
  color: #65addc;
  font-size: 50px;
  margin-right: 25px;
  cursor: pointer;
}

.discover-container {
  display: flex;
  flex-direction: row;
}

.sidebar {
  width: 250px;
  background-color: #f0f0f0;
  padding: 10px;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.sidebar .van-cell {
  margin-bottom: 30px;
  border-bottom: 1px solid #ddd;
}

.sidebar .van-cell.active {
  background-color: #409EFF;
  color: white;
  font-weight: bold;
}

.content {
  flex-grow: 1;
  padding: 10px;
}

.content h3 {
  font-size: 18px;
  color: #333;
  margin: 10px 0;
}

.highlight {
  background-color: yellow;
  padding: 5px;
  border-radius: 5px;
}
</style>
